package com.mg.controller;

import com.mg.common.Constants;
import com.mg.common.ResponseJson;
import com.mg.dto.SimpleResult;
import com.mg.dto.UserDto;
import com.mg.model.User;
import com.mg.service.SmsService;
import com.mg.service.UserService;
import com.mg.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Created by 研发二科 王永梅 .
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Value("${expiryTime}")
    private int expiryTime;

    @RequestMapping(value = {"/user"}, method = RequestMethod.GET)
    public String loginPage() {
        return "/pages/main/login";
    }


    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping(value = {"/register"}, method = RequestMethod.GET)
    public String regPage() {
        return "/pages/main/register";
    }

    @RequestMapping(value = {"/getpass"}, method = RequestMethod.GET)
    public String passPage() {
        return "/pages/main/getpass";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public User login(HttpServletRequest request, UserDto userDto, HttpServletResponse resp) {
        return userService.login(request, userDto);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseJson<User> register(HttpServletRequest request, UserDto user, HttpServletResponse resp) {
        ResponseJson<User> responseJson = new ResponseJson<>();
        String verCode = (String) request.getSession().getAttribute("verCode");

        long nowTime = System.currentTimeMillis();
        if (user.getVerCode() == null) {
            responseJson.setSuccess(500);
            responseJson.setMsg("验证码不能为空");
        } else {
            if (user.getVerCode().toUpperCase().equals(verCode)) {
                long lastVerifyCodeTime = (long) request.getSession().getAttribute("lastVerifyCodeTime");
                if ((nowTime - lastVerifyCodeTime) > expiryTime * 1000 * 60) {
                    responseJson.setSuccess(500);
                    responseJson.setMsg("验证码已过期");

                } else {
                    responseJson = userService.register(user);
                    if (responseJson.isSuccess()) {
                        HttpSession session = request.getSession();
                        session.removeAttribute(Constants.USER_INFO);
                    }
                }
            } else {
                responseJson.setSuccess(500);
                responseJson.setMsg("验证码错误");
            }
        }
        return responseJson;
    }

    @RequestMapping(value = "/editpass", method = RequestMethod.GET)
    public String editpass(HttpServletRequest request, User user, HttpServletResponse resp) {
        return "/pages/main/editpass";
    }

    @RequestMapping(value = "/editUserPass", method = RequestMethod.POST)
    @ResponseBody
    public ResponseJson<User> editUserPass(HttpServletRequest request, User user, HttpServletResponse resp) {
        String newPass = request.getParameter("newPass");
        return  userService.editPass(user, newPass);
    }

    @RequestMapping(value = "/getUserPass", method = RequestMethod.POST)
    @ResponseBody
    public ResponseJson<User> getUserPass(HttpServletRequest request, UserDto user, HttpServletResponse resp) {
        ResponseJson<User> responseJson = new ResponseJson<>();
        String verCode1 = (String) request.getSession().getAttribute("verCode");

        long nowTime = System.currentTimeMillis();
        if (user.getVerCode() == null) {
            responseJson.setSuccess(500);
            responseJson.setMsg("验证码不能为空");
        } else {
            if (user.getVerCode().toUpperCase().equals(verCode1)) {
                long lastVerifyCodeTime = (long) request.getSession().getAttribute("lastVerifyCodeTime");
                if ((nowTime - lastVerifyCodeTime) > expiryTime * 1000 * 60) {
                    responseJson.setSuccess(500);
                    responseJson.setMsg("验证码已过期");

                } else {
                    responseJson = userService.getUserPass(user);
                    if (responseJson.isSuccess()) {
                        HttpSession session = request.getSession();
                        session.removeAttribute(Constants.USER_INFO);
                    }
                }
            } else {
                responseJson.setSuccess(500);
                responseJson.setMsg("验证码错误");

            }

        }


        return responseJson;
    }

    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    @ResponseBody
    public String loginout(HttpServletRequest request, UserDto userDto) {
        HttpSession session = request.getSession();
        session.removeAttribute(Constants.USER_INFO);
        return "success";
    }

    @RequestMapping(value = "/sendCode")
    @ResponseBody
    public SimpleResult sendCode(HttpServletRequest request, String phoneNumber) {
        SimpleResult result = new SimpleResult();
        HttpSession session = request.getSession();
        String oldCode = (String) session.getAttribute("verCode");
        String verifyCode = null;
        if (oldCode == null) {
            verifyCode = VerifyCodeUtils.generateVerifyCode(6);
        } else {
            long lastVerifyCodeTime = (long) session.getAttribute("lastVerifyCodeTime");
            long nowTime = System.currentTimeMillis();
            if ((nowTime - lastVerifyCodeTime) < expiryTime * 1000 * 60) {
                result.setSuccess(false);
                result.setMsg("验证码未过期");
                return result;
            } else {
                verifyCode = VerifyCodeUtils.generateVerifyCode(6);
            }

        }
        boolean flag = smsService.sendMessage(verifyCode, phoneNumber);
        if (flag) {
            session.removeAttribute("verCode");
            session.setAttribute("verCode", verifyCode.toUpperCase());
            session.removeAttribute("lastVerifyCodeTime");
            session.setAttribute("lastVerifyCodeTime", System.currentTimeMillis());

        } else {
            result.setSuccess(false);
            result.setMsg("发送验证失败");
        }
        return result;
    }
}
